package com.example.api2interface.utils;

import com.alibaba.fastjson.JSON;
import com.example.api2interface.entity.RequestHeader;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.SortedMap;

/**
 * 验证签名工具类
 */
public class SignVerifyUtil {
    /**
     * 验证签名
     */
    public static boolean verifySign(SortedMap<String, String> sortedMap, RequestHeader requestHeader) {
        String params = requestHeader.getNonce() + requestHeader.getTimestamp() + JSON.toJSONString(sortedMap);
        return verifySign(params, requestHeader);
    }

    /**
     * 验证签名
     */
    public static boolean verifySign(String params, RequestHeader requestHeader) {
        System.out.println("客户端签名：" + requestHeader.getSign());
        if (StringUtils.isEmpty(params)) {
            return false;
        }
        System.out.println("客户端上传内容：" + params);
        String paramSign = DigestUtils.md5DigestAsHex(params.getBytes()).toUpperCase();
        System.out.println("客户端上传内容加密后的签名结果：" + paramSign);
        return requestHeader.getSign().equals(paramSign);
    }
}
